import React from 'react'
import Tagbtn from '../tagbtn/tagbtn'
import styles from './tagmodal.less'
import { Toast } from 'antd-mobile'
import Refreshicon from '../../components/refreshIcon/refreshIcon'
import {randomPick} from '../../utils/utils'


export default class Tagmodal extends React.Component {
  //state 状态初始化
  constructor(props) {
    super(props)
    this.state = {
      selectedTag: undefined,
      data: randomPick(props.data, 6),
    }
  }
  componentWillReceiveProps() {
    this.setState(() => {
      const data = randomPick(this.props.data, 6)
      return { data }
    })
  }

  confirm = () => {
    const { selectedTag } = this.state
    if (selectedTag) {
      this.props.commitAction(selectedTag)
      this.setState({
        selectedTag: undefined,
      })
    } else {
      Toast.info('请选择标签!', 1)
    }
  }
  cancel = () => {
    this.setState({
      selectedTag: undefined,
    })
    this.props.closeAction()
  }
  changTag = () => {
    let { data } = this.props
    this.setState({
      selectedTag: undefined,
      data: randomPick(data, 6, this.state.data),
    })
  }
  tagBtnClick = tagId => {
    let selectedTag = this.state.selectedTag === tagId ? undefined : tagId
    this.setState({
      selectedTag,
    })
  }

  render() {
    let { data, selectedTag } = this.state
    return (
       <div style={this.props.show ? { display: 'block' } : { display: 'none' }}> 
         <div className={styles.mask}></div> 
        <div className={styles.alert_moudel}>
          <div className={styles.tagsBox}>
            {data[0]?data.map(item => {
              if (item !== undefined) {
                return (
                  <Tagbtn
                    tag={item}
                    selectedTag={selectedTag}
                    tagClick={this.tagBtnClick}
                    key={item.tagId}
                  />
                );
              }
              return ''
            }):''}
          </div>
          <Refreshicon
          content='换一批'
          click={this.changTag}
          />
          <div className={styles.button_group}>
            <button className={styles.btn_cancel} onClick={this.cancel}>
              退出
            </button>
            <button className={styles.btn_comm} onClick={this.confirm}>
              确定
            </button>
          </div>
        </div>
       </div> 
    )
  }
}
